package com.group3.hospital.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group3.hospital.bean.Note;
import com.group3.hospital.service.NoteService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/note")
public class NoteController {

    @Resource
    private NoteService noteService;

    @RequestMapping("/NoteUi")
    public String NoteUi(Model model,
                         @RequestParam(required = false,defaultValue = "1",value = "pageNum") Integer pageNum,@RequestParam(defaultValue = "5",value = "pageSize") Integer pageSize){
        if(pageNum == null || pageNum <= 0){
            pageNum = 1;
        }
        if(pageSize == null){
            pageSize = 5;
        }
        PageHelper.startPage(pageNum,pageSize);

        try {
            List<Note> notes = noteService.queryAll();
            PageInfo<Note> pageInfo = new PageInfo<Note>(notes);
            model.addAttribute("pageInfo",pageInfo);
            model.addAttribute("notes",notes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            PageHelper.clearPage();
        }
        return "lyManage";
    }

    @RequestMapping("/NoteDel")
    public String NoteDel(@RequestParam("id") Integer id){
        try {
            noteService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/note/NoteUi";
    }

    @RequestMapping("/NoteEdit")
    public String NoteEdit(Integer id, Model model){
        try {
            Note note = noteService.queryById(id);
            model.addAttribute("note",note);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "note-edit";
    }

    @RequestMapping("/edit")
    public String edit(Note note){
        System.out.println(note);
        try {
            noteService.updatenote(note);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/note/NoteUi";
    }

    @RequestMapping("/ly")
    public String ly(){
        return "Ly";
    }

    @RequestMapping("/addnote")
    public String addnote(String noteName, String noteMessage){
        Note note = new Note();
        note.setNoteName(noteName);
        note.setNoteMessage(noteMessage);
        Date date = new Date();
        note.setNoteTime(date);
        try {
            noteService.addNote(note);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/note/ly";
    }



}
